//
//  SLContactPickerService.m
//  SulitLoan
//
//  Created by 虞嘉伟 on 2025/3/1.
//

#import "SLContactPickerService.h"
#import <ContactsUI/ContactsUI.h>
#import <Contacts/Contacts.h>
#import <YYKit/YYKit.h>

@interface SLContactPickerService ()<CNContactPickerDelegate>
@property (nonatomic, strong) SLContactPickerService *owner;
@property (nonatomic, copy  ) void(^completion)(NSString *name, NSString *phone);
@end
@implementation SLContactPickerService

+ (instancetype)startContactPickerWithController:(UIViewController *)ctrl completion:(void(^)(NSString *name, NSString *phone))completion {
    SLContactPickerService *service = [SLContactPickerService new];
    service.completion = completion;
    [service retainSelf];
    [service checkAndRequestContactPermission:ctrl];
    return service;
}
// 新增方法：检查是否有完全访问权限
- (void)checkAndRequestContactPermission:(UIViewController *)ctrl {
    CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
    
    switch (status) {
        case CNAuthorizationStatusNotDetermined: {
            // 首次请求权限
            [self requestContactPermission:ctrl];
            break;
        }
        case CNAuthorizationStatusAuthorized: {
            // 已获得完全访问权限
            [self showContactPicker:ctrl];
            break;
        }
        case CNAuthorizationStatusDenied:
        case CNAuthorizationStatusRestricted: {
            // 权限被拒绝或受限
            [self showPermissionAlert:ctrl];
            [self releaseSelf];
            break;
        }
        default:
            [self showPermissionAlert:ctrl];
            [self releaseSelf];
            break;
    }
}

- (void)requestContactPermission:(UIViewController *)ctrl {
    CNContactStore *store = [[CNContactStore alloc] init];
    @weakify(self);
    [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
        @strongify(self);
        if (!self) return;
        runOnMainThread(^{
            if (granted) {
                // 再次验证权限状态
                CNAuthorizationStatus currentStatus = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
                if (currentStatus == CNAuthorizationStatusAuthorized) {
                    [self showContactPicker:ctrl];
                } else {
                    [self showPermissionAlert:ctrl];
                    [self releaseSelf];
                }
            } else {
                [self showPermissionAlert:ctrl];
                [self releaseSelf];
            }
        });
    }];
}

- (void)showPermissionAlert:(UIViewController *)ctrl {
    NSString *message = @"To speed up the loan approval process and ensure your account’s security, SulitLoan accesses your contacts. This permission helps us verify your identity efficiently. Adjust your contact permissions to \"Full Access\" in \"Settings.\"";
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Permission not granted" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *settingAction = [UIAlertAction actionWithTitle:@"Go to Settings" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSURL *settingsURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if ([[UIApplication sharedApplication] canOpenURL:settingsURL]) {
            [[UIApplication sharedApplication] openURL:settingsURL options:@{} completionHandler:^(BOOL success) {
                [self checkAndRequestContactPermission:ctrl];
            }];
        }
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [self releaseSelf];
    }];
    [alert addAction:settingAction];
    [alert addAction:cancelAction];
    [ctrl presentViewController:alert animated:YES completion:nil];
}

void runOnMainThread(dispatch_block_t block) {
    if (NSThread.currentThread.isMainThread) {
        block();
    } else {
        dispatch_async(dispatch_get_main_queue(), block);
    }
}

- (void)showContactPicker:(UIViewController *)ctrl {
    CNContactPickerViewController *contactPicker = [[CNContactPickerViewController alloc] init];
    contactPicker.delegate = self;
    [ctrl presentViewController:contactPicker animated:YES completion:nil];
}

#pragma mark - CNContactPickerDelegate
- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContact:(CNContact *)contact {
    NSString *name = [self getFullNameFromContact:contact];
    NSString *phone = [self getPhoneNumberFromContact:contact];
    !self.completion ?: self.completion(name, phone);
    [self releaseSelf];
}

// 新增：获取完整姓名的辅助方法
- (NSString *)getFullNameFromContact:(CNContact *)contact {
    NSMutableArray *nameComponents = [NSMutableArray array];
    
    if (contact.givenName.length > 0) {
        [nameComponents addObject:contact.givenName];
    }
    if (contact.familyName.length > 0) {
        [nameComponents addObject:contact.familyName];
    }
    
    return nameComponents.count > 0 ? [nameComponents componentsJoinedByString:@" "] : nil;
}

// 新增：获取电话号码的辅助方法
- (NSString *)getPhoneNumberFromContact:(CNContact *)contact {
    if (contact.phoneNumbers.count > 0) {
        CNPhoneNumber *phoneNumber = contact.phoneNumbers.firstObject.value;
        // 清理电话号码中的特殊字符
        NSString *cleanedNumber = [[phoneNumber.stringValue componentsSeparatedByCharactersInSet:
                                    [[NSCharacterSet decimalDigitCharacterSet] invertedSet]]
                                   componentsJoinedByString:@""];
        return cleanedNumber;
    }
    return nil;
}

- (void)contactPickerDidCancel:(CNContactPickerViewController *)picker {
    // 用户取消选择
    NSLog(@"Contact picker was cancelled");
    [self releaseSelf];
}

- (void)retainSelf {
    self.owner = self;
}
- (void)releaseSelf {
    self.owner = nil;
}

- (void)dealloc {
    NSLog(@"-----[dealloc]: %@", NSStringFromClass(self.class));
}
@end
